#include "head.h"

// 子线程处理文件的上传和下载逻辑
void *file_transfer(void *arg) {
    // 此处编写文件上传和下载的逻辑
    printf("这是子线程\n");
    cur_info *info = (cur_info*)arg;
    char cmd_backup[1024] = {0}; // 命令备份
    memcpy(cmd_backup, info->cmd, sizeof(cmd_backup)); // 备份命令
    printf("cmd = %s, cmd backup = %s\n", info->cmd, cmd_backup);

    char *ip = "192.168.222.130";
    char *port = "8080";


    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(socket_fd, -1, "socket");
    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);

    int res_conn = connect(socket_fd,(struct sockaddr *)&sockaddr,sizeof(sockaddr));
    ERROR_CHECK(res_conn, -1, "connect");
    printf("conn = %d\n", res_conn);
    
    int flag = 1;
    send(socket_fd, &flag, sizeof(int), 0);
    usleep(1000);
    send(socket_fd, info->token, sizeof(info->token), 0);
    send(socket_fd, info->cur_path, sizeof(info->cur_path), 0);
    // 分割命令头和命令体
    char *cmd_head = strtok(info->cmd, " ");
    printf("cmd_head = %s\n", cmd_head);
    char *cmd_body = strtok(NULL, "\n");
    printf("cmd_body = %s\n", cmd_body);

    if (strcmp(cmd_head, "upload") == 0){ // 进行上传文件的逻辑
        printf("cmd_head = %s, %ld\n", cmd_head, strlen(cmd_head));
        //文件名
        char filename[100] = {0};
        strncpy(filename, cmd_body, strlen(cmd_body));
        printf("file name : %s\n", filename);
        
        int fd = open(filename, O_RDONLY);
        if(fd == -1){
            printf("文件不存在\n");
            return 0;
        }
        send(socket_fd, cmd_backup, 1024, MSG_NOSIGNAL); 
        send_bigfile(socket_fd, filename);
        printf("upload over\n");
    }
    else { // 进行下载文件的逻辑
        printf("download start\n");
        send(socket_fd, cmd_backup, 1024, MSG_NOSIGNAL); // 将命令发给服务器

        char filename[100]={0};
        strncpy(filename, cmd_body, strlen(cmd_body));
        //printf("%s\n", filename);
        recv_bigfile(socket_fd, filename);
        printf("download over\n");
    }
    return NULL;
}
